package com.knife.tools;

import java.util.Date;
import java.util.List;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import com.knife.news.logic.impl.SiteServiceImpl;
import com.knife.news.logic.impl.UserServiceImpl;
import com.knife.news.object.Site;
import com.knife.news.object.User;
import com.knife.util.CommUtil;
import com.knife.web.WebForm;

public class MailUtil {

	private SiteServiceImpl sitedao = SiteServiceImpl.getInstance();
	private UserServiceImpl mailuserdao = UserServiceImpl.getInstance();
	
	public boolean send(WebForm form) {
		String Subject = CommUtil.null2String(form.get("subject"));// 标题
		String messageText = CommUtil.null2String(form.get("message"));// 发送内容
		boolean sessionDebug = false;
		try {
			Site mysite = sitedao.getSite();
			String mailserver = mysite.getMailserver();// 发出邮箱的服务器
			String From = mysite.getMailuser();// 发出的邮箱
			String pass = mysite.getMailpass();
			List<User> toUsers =mailuserdao.getUsersBySql("k_popedom='1'");
			// 设定所要用的Mail 服务器和所使用的传输协议
			java.util.Properties props = System.getProperties();
			props.put("mail.host", mailserver);
			props.put("mail.transport.protocol", "smtp");
			props.put("mail.smtp.auth", "true");// 指定是否需要SMTP验证

			// 产生新的Session 服务
			javax.mail.Session mailSession = javax.mail.Session
					.getDefaultInstance(props, null);
			mailSession.setDebug(sessionDebug);
			Message msg = new MimeMessage(mailSession);

			// 设定发邮件的人
			msg.setFrom(new InternetAddress(From));

			InternetAddress[] address = new InternetAddress[toUsers.size()];
			// 设定收信人的信箱
			for(int i=0;i< toUsers.size();i++){
				User ruser = (User)toUsers.get(i);
				//to+=ruser.getEmail()+" ; ";
				address[i]=new InternetAddress((String)ruser.getEmail());
			}
			//address = InternetAddress.parse(to, false);
			msg.setRecipients(Message.RecipientType.TO, address);

			// 设定信中的主题
			msg.setSubject(Subject);

			// 设定送信的时间
			msg.setSentDate(new Date());

			Multipart mp = new MimeMultipart();
			MimeBodyPart mbp = new MimeBodyPart();

			// 设定邮件内容的类型为 text/plain 或 text/html
			mbp.setContent(messageText,"text/html; charset=utf-8");
			mp.addBodyPart(mbp);
			msg.setContent(mp);

			Transport transport = mailSession.getTransport("smtp");
			// //请填入你的邮箱用户名和密码,千万别用我的^_^
			transport.connect(mailserver, From, pass);// 设发出邮箱的用户名、密码
			transport.sendMessage(msg, msg.getAllRecipients());
			transport.close();
			//System.out.println("邮件已顺利发送");
			return true;

		} catch (MessagingException mex) {
			mex.printStackTrace();
			//System.out.println(mex);
			return false;
		}

	}
}
